﻿/*
 * Created by SharpDevelop.
 * User: aaa
 * Date: 2012/6/26
 * Time: 15:02
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace QuickFileCodeReplacer
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}

		private Dictionary<String,String> dict = new Dictionary<String,String>();
		void MainFormLoad(object sender, EventArgs e)
		{
			dict.Add("import java.io.File;","import com.quickfile.File;");
			dict.Add("import java.io.FileInputStream;","import com.quickfile.FileInputStream;");
			dict.Add("import java.io.FileOutputStream;","import com.quickfile.FileOutputStream;");
			dict.Add("import java.io.FileReader;","import com.quickfile.FileReader;");
			dict.Add("import java.io.FileWriter;","import com.quickfile.FileWriter;");
			dict.Add("import java.io.*;","import com.quickfile.*;");
			dict.Add("import java.util.zip.ZipFile;","import com.quickfile.util.ZipFile;");
			dict.Add("new File(","File.newInstance(");
			dict.Add("new FileInputStream(","FileInputStream.newInstance(");
			dict.Add("new FileOutputStream(","FileOutputStream.newInstance(");
		}
		
		void BtnSelectPathClick(object sender, EventArgs e)
		{
			OpenFileDialog ofd = new OpenFileDialog();
			DialogResult dr = ofd.ShowDialog();
			if(dr == DialogResult.Cancel)
				return;
			this.txtSourceCodePath.Text = ofd.FileName;
		}
		
		void BtnStartClick(object sender, EventArgs e)
		{
			try
			{
				btnStart.Enabled = false;
				DirectoryInfo di = new DirectoryInfo(this.txtSourceCodePath.Text);
				if(!di.Exists){
					MessageBox.Show("Code path not exist!");
					return;
				}
				FileInfo[] fis = di.GetFiles("*.java", SearchOption.AllDirectories);
				int fileCount = fis.Length;
				for(int i=0;i<fileCount;i++)
				{
					FileInfo fi = fis[i];
					String fileContent = File.ReadAllText(fi.FullName,System.Text.Encoding.UTF8);
					if(!String.IsNullOrEmpty(fileContent)){
						foreach(String key in dict.Keys)
						{
							fileContent = fileContent.Replace(key,dict[key]);
						}
						File.WriteAllText(fi.FullName,fileContent,new System.Text.UTF8Encoding(false));
					}
					if(i % 10 == 0)
					{
						pbMain.Value = (i + 1) * 100 / fileCount;
						Application.DoEvents();
					}
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show("处理过程中出错，原因：" + ex);
			}
			finally
			{
				btnStart.Enabled = true;;
			}
		}
	}
}
